package com.origin.src.boot.servlet;

import org.apache.catalina.Wrapper;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.context.WebServerGracefulShutdownLifecycle;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatWebServer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

//@Component
public class ServletIn implements ApplicationListener<ApplicationReadyEvent> {

    WebServerGracefulShutdownLifecycle webServerGracefulShutdownLifecycle;

    public void in() throws NoSuchFieldException, IllegalAccessException {
        System.out.println("in" + webServerGracefulShutdownLifecycle);
        Field field = WebServerGracefulShutdownLifecycle.class.getDeclaredField("webServer");
        field.setAccessible(true);
        TomcatWebServer webServer = (TomcatWebServer) field.get(webServerGracefulShutdownLifecycle);
        Tomcat tomcat = webServer.getTomcat();
//        tomcat.addContext("/s", "");
//        tomcat.addServlet("/s", "servletTest", new ServletTest());
        StandardContext standardContext = new StandardContext();
        standardContext.setPath("/x");
        tomcat.getHost().addChild(standardContext);
        standardContext.setName("x");

        StandardContext context = standardContext;//(StandardContext) tomcat.getHost().findChildren()[0];

        Wrapper defaultServlet = context.createWrapper();
        defaultServlet.setName("default");
        defaultServlet.setServletClass("com.origin.src.boot.servlet");
//        defaultServlet.addInitParameter("debug", "0");
//        defaultServlet.addInitParameter("listings", "false");
        defaultServlet.setLoadOnStartup(1);
        // Otherwise the default location of a Spring DispatcherServlet cannot be set
        defaultServlet.setOverridable(true);
        context.addChild(defaultServlet);
        context.addServletMappingDecoded("/sss", "default");
    }


    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        webServerGracefulShutdownLifecycle = event.getApplicationContext().getBean(WebServerGracefulShutdownLifecycle.class);
        try {
            in();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}
